require 'gosu'
require 'utils'
require 'map'
require 'zindex'

class EvilDuke
  SIZE=50
  
  @@bugs=Array.new
  attr_reader :x, :y
  
  def initialize(window,right_image, left_image,x, y)
    @window=window
    @bug_right = right_image
    @bug_left = left_image
    @x, @y = x, y  
    @step= +1
    @velocity=rand(4) +1
    @current_sprite=@bug_right
  end

  def update(player)
    distance_x = (player.x - @x).abs
    distance_y = (player.y - @y).abs
    if distance_y < SIZE / 2 && distance_x < SIZE - 5  #since the sprite is not a perfect square, substracting five is a better fit for collisions       
      player.kill
    else
      @velocity.times do 
        if @window.map.would_fit(x,y,@step, 0,SIZE,0) 
          @x += @step
        else
          @step *= -1
          break
        end  
      end    
      @current_sprite = @step > 0 ? @bug_right : @bug_left      
    end
  end
    
  def draw(screen_x, screen_y)    
    @current_sprite.draw(@x - screen_x , @y - screen_y - SIZE / 2, Zindex::BUG, 1, 1.0)
  end

  def EvilDuke.load_from_map(window)
    @@bugs=Array.new
    bug_right,bug_left = Image.load_tiles(window, "#{cur_dir}/graphics/duke_running.png", SIZE, SIZE, false)
    coords=window.map.coords_of_tokens(Map::Tokens::BUG)
    coords.each do |coord|
      @@bugs.push(EvilDuke.new(window,bug_right,bug_left, coord[0] * SIZE + SIZE / 2, coord[1] * SIZE + SIZE / 2))
    end
 end
    
  def EvilDuke.bugs
    return @@bugs
  end
  
  def EvilDuke.update_bugs(player)
    @@bugs.each {|bug| bug.update(player)}
  end
  
  def EvilDuke.draw_bugs(screen_x,screen_y)
    @@bugs.each {|bug| bug.draw(screen_x,screen_y)}
  end
  
    
end
